package ru.papergames.battleserver.network.clientpackets.flashuser;

import org.apache.log4j.Logger;
import ru.papergames.battleserver.model.*;
import ru.papergames.battleserver.model.auth.AuthThreadController;
import ru.papergames.battleserver.model.auth.WaitingForAuthUser;
import ru.papergames.battleserver.network.PaperGameClient;
import ru.papergames.battleserver.network.serverpackets.flashuser.ActionFailed;
import ru.papergames.battleserver.network.serverpackets.flashuser.AuthFailedUserAlreadyOnline;
import ru.papergames.battleserver.network.serverpackets.flashuser.AuthorizationPassed;
import ru.papergames.battleserver.network.serverpackets.webserver.FlashUserConnected;
import ru.papergames.common.form.PcPlayerForm;

/**
 * @author: ATroshanin
 * Date: 15.06.2010
 * Time: 14:06:07
 */
public class AuthLogin extends PaperGameClientPacket {

    private static final Logger log = Logger.getLogger(AuthLogin.class.getName());

    private int playerId;
    private int secretKey;

    @Override
    protected void readImpl() {
        playerId = readD();
        secretKey = readD();
    }

    @Override
    protected void runImpl() {
        log.info("AuthLogin for user: " + playerId);
        AbstractPaperGameUser existingUser = UsersManager.getInstance().getPaperGameUser(playerId);
        if (existingUser != null && !existingUser.isDetached()) {
            log.warn("ALARM: user[" + playerId + "] tried to connect with second window. DUPLICATE CONNECTION");
            sendPacket(AuthFailedUserAlreadyOnline.STATIC_PACKET);
            return;
        }
        ConnectingFlashUser connectingUser = UsersManager.getInstance().popFlashUserFromNewUsers(playerId);
        
        if (connectingUser != null) {
            // ok now we sure that web server already registered current user on this messaging server
            authorizeUser(getClient(), connectingUser, secretKey);
        } else {
            log.info("No info about user[" + playerId + "]. Wating for his data");
            // web server has not registered current user on this messaging server
            // so we have to add this user to scheduler which will checks if this user
            // is registered by web server and then auth him.
            AuthThreadController.getInstance().addUserToAuthProcess(new WaitingForAuthUser(playerId, secretKey, getClient()));
        }
    }

    @Override
    public String getType() {
        return "[c] AuthLogin[" + AUTH_LOGIN_PACKET_ID + "]";
    }

    public static void authorizeUser(PaperGameClient client, ConnectingFlashUser connectingUser, int secretKey) {
        PcPlayerForm player = connectingUser.getPlayer();
        log.info("checking player[" + player.getId() + "]");
        if (connectingUser.getSecretKey() != secretKey) {
            log.warn("Authorization FAILED for player: " + player.getId());
            client.sendPacket(ActionFailed.STATIC_PACKET);
            return;
        }

        client.sendPacket(AuthorizationPassed.STATIC_PACKET);

        PaperGameFlashUser user = new PaperGameFlashUser(connectingUser.getPlayer(), client);
        client.setState(PaperGameClient.GameClientState.AUTHED);
        client.setUser(user);
        UsersManager.getInstance().addConnectedUserToRoom(user);
        log.info("Authorization PASSED for player: " + connectingUser.getPlayer().getId());
        WebServerClientHolder.getInstance().sendPacketToWebServer(new FlashUserConnected(user));
    }
}
